package com.miaoke.net;

import com.miaoke.ServiceDispatch;
import com.miaoke.entity.RpcTransferDto;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class RpcRequestHandler implements  Runnable {
    private Socket socket;

    public RpcRequestHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        ObjectInputStream ois=null;
        ObjectOutputStream oos=null;
        try {
            ois=new ObjectInputStream(socket.getInputStream());
            RpcTransferDto dto = (RpcTransferDto) ois.readObject();
            Object retObj = ServiceDispatch.dispatch(dto);
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(retObj);
            oos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (oos!=null)
                    oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(ois!=null){
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
